#pragma once

#include <iostream>
#include <string>
#include <thread>
#include <functional>
#include "inetapi.hpp"

class http_server : public inet::tcp::server
{
public:
    using func_t = std::function<std::string(const std::string&)>;

public:
    http_server(func_t cb, int port) : _cb(cb), server(port)
    {}

    ~http_server()
    {}

    void init()
    {}

    void start()
    {
        while (true)
        {
            std::string cip;
            uint16_t cport;
            int sock = accept(&cip, &cport);
            if (sock < 0)
                continue;

            std::thread th(&http_server::handler_http_request, this, sock, cip, cport);
            th.detach();
        }
    }

    void handler_http_request(int sock, const std::string& cip, uint16_t cport)
    {
        while (true)
        {
            std::string msg;
            ssize_t s = recv(sock, &msg, 4096);
            if (s > 0)
            {
                std::string rsp = _cb(msg);
                send(sock, rsp);
            }
            else
            {
                break;
            }
        }
    }

private: 
    func_t _cb;
};
